<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          type="text" 
          v-model="keyword" 
          placeholder="搜索药品名称、症状" 
          confirm-type="search"
          @confirm="handleSearch"
          focus
        />
        <text class="clear-icon" v-if="keyword" @tap="clearKeyword">×</text>
      </view>
      <text class="cancel-btn" @tap="goBack">取消</text>
    </view>

    <!-- 搜索内容区域 -->
    <view class="search-content">
      <!-- 搜索历史 -->
      <view class="search-history" v-if="!keyword && searchHistory.length > 0 && !searching">
        <view class="section-header">
          <text class="title">搜索历史</text>
          <text class="clear-btn" @tap="clearHistory">清空</text>
        </view>
        <view class="history-list">
          <view 
            class="history-item" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @tap="searchByHistory(item)"
          >
            <text class="history-text">{{ item }}</text>
            <text class="delete-btn" @tap.stop="deleteHistory(index)">×</text>
          </view>
        </view>
      </view>

      <!-- 热门搜索 -->
      <view class="hot-search" v-if="!keyword && !searching">
        <view class="section-header">
          <text class="title">热门搜索</text>
        </view>
        <view class="hot-list">
          <view 
            class="hot-item" 
            v-for="(item, index) in hotSearches" 
            :key="index"
            @tap="searchByHistory(item)"
          >
            <text class="hot-rank" v-if="index < 3">{{ index + 1 }}</text>
            <text class="hot-rank normal" v-else>{{ index + 1 }}</text>
            <text class="hot-text">{{ item }}</text>
          </view>
        </view>
      </view>

      <!-- 搜索建议 -->
      <view class="search-suggestions" v-if="keyword && suggestions.length > 0 && !searching">
        <view 
          class="suggestion-item" 
          v-for="(item, index) in suggestions" 
          :key="index"
          @tap="searchBySuggestion(item)"
        >
          <text class="suggestion-icon">🔍</text>
          <text class="suggestion-text">{{ item }}</text>
        </view>
      </view>

      <!-- 搜索结果 -->
      <view class="search-results" v-if="searching">
        <view class="filter-bar">
          <view 
            class="filter-item" 
            :class="{ active: currentFilter === 'all' }"
            @tap="switchFilter('all')"
          >
            综合
          </view>
          <view 
            class="filter-item" 
            :class="{ active: currentFilter === 'sales' }"
            @tap="switchFilter('sales')"
          >
            销量
          </view>
          <view 
            class="filter-item" 
            :class="{ active: currentFilter === 'price' }"
            @tap="switchFilter('price')"
          >
            价格
            <text class="sort-icon">{{ sortDirection === 'asc' ? '↑' : '↓' }}</text>
          </view>
        </view>

        <scroll-view 
          class="result-list" 
          scroll-y 
          @scrolltolower="loadMore"
          :refresher-enabled="true"
          @refresherrefresh="refresh"
        >
          <view class="medicine-items">
            <view 
              class="medicine-item"
              v-for="(medicine, index) in searchResults"
              :key="index"
              @tap="goToDetail(medicine.medicine_id)"
            >
              <image :src="medicine.image_url || '/static/medicine-default.png'" mode="aspectFill" class="medicine-image"></image>
              <view class="medicine-info">
                <view class="medicine-tag" v-if="medicine.status === 0">OTC</view>
                <view class="medicine-tag rx" v-else-if="medicine.status === 1">RX</view>
                <text class="medicine-name">{{ medicine.medicine_name }}</text>
                <text class="medicine-desc">{{ medicine.indications }}</text>
                <view class="medicine-price-row">
                  <text class="price">¥{{ medicine.price || '6.5' }}</text>
                  <view class="add-btn" @tap.stop="addToCart(medicine)">+</view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view class="loading-state" v-if="loading">加载中...</view>
          <view class="no-more" v-if="!hasMore && !loading && searchResults.length > 0">没有更多了</view>
          <view class="empty-result" v-if="!loading && searchResults.length === 0 && searching">
            <image src="/static/empty-search.png" mode="aspectFit" class="empty-image"></image>
            <text class="empty-text">没有找到相关药品</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { medicineApi } from '@/api/medicine'

export default {
  data() {
    return {
      keyword: '',
      searchHistory: [],
      hotSearches: ['感冒药', '退烧药', '消炎药', '止痛药', '胃药', '维生素', '眼药水', '创可贴', '消毒液', '口罩'],
      suggestions: [],
      searching: false,
      searchResults: [],
      currentFilter: 'all',
      sortDirection: 'desc',
      page: 1,
      pageSize: 10,
      loading: false,
      hasMore: true
    }
  },
  
  onLoad() {
    this.loadSearchHistory()
  },
  
  watch: {
    keyword(val) {
      if (val) {
        this.getSuggestions(val)
      } else {
        this.suggestions = []
        this.searching = false
      }
    }
  },
  
  methods: {
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory') || []
      this.searchHistory = history
    },
    
    saveSearchHistory(keyword) {
      if (!keyword) return
      
      let history = uni.getStorageSync('searchHistory') || []
      
      // 如果已存在，先删除旧记录
      const index = history.indexOf(keyword)
      if (index !== -1) {
        history.splice(index, 1)
      }
      
      // 添加到历史记录最前面
      history.unshift(keyword)
      
      // 最多保存10条记录
      if (history.length > 10) {
        history = history.slice(0, 10)
      }
      
      uni.setStorageSync('searchHistory', history)
      this.searchHistory = history
    },
    
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('searchHistory')
            this.searchHistory = []
          }
        }
      })
    },
    
    deleteHistory(index) {
      let history = [...this.searchHistory]
      history.splice(index, 1)
      uni.setStorageSync('searchHistory', history)
      this.searchHistory = history
    },
    
    clearKeyword() {
      this.keyword = ''
      this.searching = false
      this.searchResults = []
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    getSuggestions(keyword) {
      // 模拟搜索建议
      if (!keyword) {
        this.suggestions = []
        return
      }
      
      // 这里应该调用API获取搜索建议
      // 示例数据
      this.suggestions = [
        keyword,
        keyword + '胶囊',
        keyword + '片',
        keyword + '口服液'
      ]
    },
    
    searchByHistory(keyword) {
      this.keyword = keyword
      this.handleSearch()
    },
    
    searchBySuggestion(suggestion) {
      this.keyword = suggestion
      this.handleSearch()
    },
    
    handleSearch() {
      if (!this.keyword.trim()) return
      
      this.saveSearchHistory(this.keyword)
      this.searching = true
      this.searchResults = []
      this.page = 1
      this.hasMore = true
      this.loadSearchResults()
    },
    
    switchFilter(filter) {
      if (this.currentFilter === filter && filter === 'price') {
        // 如果点击的是已选中的价格排序，则切换排序方向
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'
      } else {
        this.currentFilter = filter
        if (filter === 'price') {
          this.sortDirection = 'asc'
        }
      }
      
      this.searchResults = []
      this.page = 1
      this.hasMore = true
      this.loadSearchResults()
    },
    
    async loadSearchResults() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      try {
        const params = {
          keyword: this.keyword,
          page: this.page,
          pageSize: this.pageSize,
          sort: this.currentFilter !== 'all' ? this.currentFilter : undefined,
          order: this.sortDirection
        }
        
        // 调用API获取搜索结果
        const res = await medicineApi.getMedicineList(params)
        
        if (res.data && res.data.list) {
          if (this.page === 1) {
            this.searchResults = res.data.list
          } else {
            this.searchResults = [...this.searchResults, ...res.data.list]
          }
          this.hasMore = res.data.list.length === this.pageSize
          this.page++
        }
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async refresh() {
      this.page = 1
      this.hasMore = true
      await this.loadSearchResults()
      uni.stopPullDownRefresh()
    },
    
    loadMore() {
      this.loadSearchResults()
    },
    
    goToDetail(medicineId) {
      uni.navigateTo({
        url: `/pages/pharmacy/detail?id=${medicineId}`
      })
    },
    
    addToCart(medicine) {
      // 添加到购物车
      let cart = uni.getStorageSync('medicineCart') || []
      const existItem = cart.find(item => item.medicine_id === medicine.medicine_id)
      
      if (existItem) {
        existItem.quantity += 1
      } else {
        cart.push({
          medicine_id: medicine.medicine_id,
          medicine_name: medicine.medicine_name,
          image_url: medicine.image_url,
          price: medicine.price || 6.5,
          quantity: 1,
          specification: medicine.specification
        })
      }
      
      uni.setStorageSync('medicineCart', cart)
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      })
    }
  }
}
</script>

<style lang="scss">
.search-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .search-header {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #fff;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    
    .search-box {
      flex: 1;
      display: flex;
      align-items: center;
      height: 72rpx;
      background-color: #f5f5f5;
      border-radius: 36rpx;
      padding: 0 20rpx;
      margin-right: 20rpx;
      
      .search-icon {
        margin-right: 10rpx;
        font-size: 32rpx;
        color: #999;
      }
      
      input {
        flex: 1;
        height: 72rpx;
        font-size: 28rpx;
      }
      
      .clear-icon {
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .cancel-btn {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .search-content {
    padding-top: 112rpx;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      
      .title {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }
      
      .clear-btn {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .search-history {
      background-color: #fff;
      margin-bottom: 20rpx;
      
      .history-list {
        display: flex;
        flex-wrap: wrap;
        padding: 0 20rpx 30rpx;
        
        .history-item {
          display: flex;
          align-items: center;
          background-color: #f5f5f5;
          border-radius: 30rpx;
          padding: 10rpx 20rpx;
          margin: 0 20rpx 20rpx 0;
          
          .history-text {
            font-size: 26rpx;
            color: #666;
            margin-right: 10rpx;
          }
          
          .delete-btn {
            width: 30rpx;
            height: 30rpx;
            line-height: 30rpx;
            text-align: center;
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
    
    .hot-search {
      background-color: #fff;
      
      .hot-list {
        padding: 0 30rpx 30rpx;
        
        .hot-item {
          display: flex;
          align-items: center;
          padding: 20rpx 0;
          border-bottom: 1rpx solid #f5f5f5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .hot-rank {
            width: 40rpx;
            height: 40rpx;
            line-height: 40rpx;
            text-align: center;
            background-color: #ff5500;
            color: #fff;
            font-size: 24rpx;
            border-radius: 6rpx;
            margin-right: 20rpx;
            
            &.normal {
              background-color: #999;
            }
          }
          
          .hot-text {
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    }
    
    .search-suggestions {
      background-color: #fff;
      
      .suggestion-item {
        display: flex;
        align-items: center;
        padding: 20rpx 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .suggestion-icon {
          margin-right: 20rpx;
          font-size: 28rpx;
          color: #999;
        }
        
        .suggestion-text {
          font-size: 28rpx;
          color: #333;
        }
      }
    }
    
    .search-results {
      .filter-bar {
        display: flex;
        background-color: #fff;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #eee;
        
        .filter-item {
          flex: 1;
          text-align: center;
          font-size: 28rpx;
          color: #666;
          position: relative;
          
          &.active {
            color: #ff5500;
            font-weight: bold;
          }
          
          .sort-icon {
            margin-left: 4rpx;
          }
        }
      }
      
      .result-list {
        height: calc(100vh - 220rpx);
        
        .medicine-items {
          padding: 20rpx;
          
          .medicine-item {
            display: flex;
            padding: 20rpx;
            background-color: #fff;
            margin-bottom: 20rpx;
            border-radius: 12rpx;
            
            .medicine-image {
              width: 160rpx;
              height: 160rpx;
              border-radius: 8rpx;
              margin-right: 20rpx;
            }
            
            .medicine-info {
              flex: 1;
              position: relative;
              
              .medicine-tag {
                display: inline-block;
                padding: 4rpx 12rpx;
                background-color: #e1f5fe;
                color: #03a9f4;
                font-size: 22rpx;
                border-radius: 4rpx;
                margin-bottom: 10rpx;
                
                &.rx {
                  background-color: #ffebee;
                  color: #f44336;
                }
              }
              
              .medicine-name {
                font-size: 28rpx;
                color: #333;
                font-weight: bold;
                margin-bottom: 10rpx;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
              }
              
              .medicine-desc {
                font-size: 24rpx;
                color: #999;
                margin-bottom: 20rpx;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
              }
              
              .medicine-price-row {
                display: flex;
                justify-content: space-between;
                align-items: center;
                
                .price {
                  font-size: 32rpx;
                  color: #ff5500;
                  font-weight: bold;
                }
                
                .add-btn {
                  width: 48rpx;
                  height: 48rpx;
                  line-height: 42rpx;
                  text-align: center;
                  background-color: #ff5500;
                  color: #fff;
                  font-size: 36rpx;
                  border-radius: 50%;
                }
              }
            }
          }
        }
        
        .loading-state, .no-more {
          text-align: center;
          padding: 30rpx;
          color: #999;
          font-size: 24rpx;
        }
        
        .empty-result {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding-top: 200rpx;
          
          .empty-image {
            width: 240rpx;
            height: 240rpx;
            margin-bottom: 40rpx;
          }
          
          .empty-text {
            font-size: 28rpx;
            color: #999;
          }
        }
      }
    }
  }
}
</style> 